<?php


namespace app\middleware;

use app\util\ReturnCode;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class AdminAuth implements MiddlewareInterface {

    /**
     * ApiAuth鉴权
     * @param Request $request
     * @param callable $next
     * @return Response
     */
    public function process(Request $request, callable $next) : Response
    {
        $ApiAuth = $request->header('Api-Auth', '');
        if ($ApiAuth) {
            $userInfo = cache('Login' . $ApiAuth);
            if ($userInfo) {
                $userInfo = json_decode($userInfo, true);
                session('admin_user_id',$userInfo['id']);
            }
            if (!$userInfo || !isset($userInfo['id'])) {
                return json([
                    'code' => ReturnCode::AUTH_ERROR,
                    'msg'  => 'ApiAuth不匹配',
                    'data' => []
                ]);
            }
            return $next($request);
        } else {
            return json([
                'code' => ReturnCode::AUTH_ERROR,
                'msg'  => '缺少ApiAuth',
                'data' => []
            ]);
        }
    }
}
